<?php


namespace app\admin\model;


use app\common\model\Base;
use app\common\model\member\money\Log;
use app\common\model\product\Order;
use app\common\model\system\Level;
use Exception;
use mb\helper\Collection;
use think\Db;

class Member
{
    protected static $table = 'members';
    /**
     * @param array $row
     * @return bool|int|string
     */
    public static function add(array $row)
    {
        $newRow = Collection::elements([
            'username',
            'nickname',
            'password',
            'realName',
            'salt',
            'phone',
            'ghost',
            'withdrawal',
            'memo',
            'staffId',
            'teamId',
            'parentId',
            'token',
            'v1',
            'v2',
            'v3',
            'level',
        ], $row);
        $newRow['money'] = 0;
        $newRow['agChange'] = 1;
        $newRow['status'] = empty($row['status'])?'normal':$row['status'];
        $newRow['withdrawal'] = empty($row['withdrawal'])?'normal':$row['status'];
        $newRow['avatar'] = '/avatar.png';
        $newRow['timeCreated'] = time();
        $newRow = Collection::keyStyle($newRow, Collection::NAME_STYLE_C);
        try {
            return Db::table(self::$table)
                ->insertGetId($newRow);
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
    }

    /**
     * @param $filter
     * @return array|Error
     */
    public static function fetch($filter,$connect = null)
    {
        $where = self::parseFilters($filter);
        try {
            if (empty($connect)) {
                $connect = Db::connect();
            }
            $row = $connect->table(self::$table)
                ->where($where)
                ->find();
            if (!empty($row)) {
                $row['time_created'] *= 1000;
                return Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return [];
    }

    /**
     * @param $filter
     * @return bool|Error
     */
    public static function remove($filter)
    {
        $where = self::parseFilters($filter);
        try {
            $offect = Db::table(self::$table)
                ->where($where)
                ->delete();
            if ($offect === 1) {
                return true;
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return $offect;
    }

    /**
     * @param $filter
     * @param $newState
     * @return bool|Error
     */
    public static function update($filter, $newState,$connect = '')
    {
        $where = self::parseFilters($filter);
        try {
            if (empty($connect)) {
                $connect = Db::connect();
            }
            $offect = $connect->table(self::$table)
                ->where($where)
                ->update($newState);
            if ($offect === 1) {
                return true;
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return $offect;
    }

    /**
     * @param $filter
     * @return array
     */
    public static function parseFilters($filter)
    {
        $where = [];
        if (is_array($filter)) {
            if (!empty($filter['id'])) {
                $where[] = ['id', '=', $filter['id']];
            }
            if (!empty($filter['ids'])) {
                $where[] = ['id', 'in', $filter['ids']];
            }
            if (!empty($filter['username'])) {
                $where[] = ['username', '=', $filter['username']];
            }
            if (!empty($filter['token'])) {
                $where[] = ['token', '=', $filter['token']];
            }
            if (empty($where)) {
                throw error(-10, '参数错误必须指定id');
            }
        } else {
            $where[] = ['id', '=', intval($filter)];
        }
        return $where;
    }

    public static function sumFiled($filters,$filed)
    {
        $where = self::parseSearchFilters($filters);
        try {
            return Db::table(self::$table)->where($where)->sum($filed);
        }catch (Exception $e) {
            return 0;
        }
    }

    /**
     * @param array $filters
     * @param int $pIndex
     * @param int $pSize
     * @param int $total
     * @return array|Error
     */
    public static function search(array $filters, int $pIndex = 0, int $pSize = 10, int &$total = 0)
    {
        $where = self::parseSearchFilters($filters);
        try {
            if (!empty($pIndex)) {
                $total = Db::table(self::$table)
                    ->where($where)
                    ->count();
            }
            $query = Db::table(self::$table)
                ->where($where);
            if (!empty($pIndex)) {
                $query->page($pIndex, $pSize);
            }
            if (!empty($filters['order'])) {
                $query->order($filters['order']);
            }
            $dataSet = $query->select();
            if (!$dataSet->isEmpty()) {
                return $dataSet->map(
                    function ($row) {
                        $row['time_created'] *= 1000;
                        $row['time_heart'] *= 1000;
                        $row = Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
                        return $row;
                    }
                )->toArray();
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return [];
    }

    public static function parseSearchFilters($filters)
    {
        $where = [];
        if (isset($filters['ghost'])) {
            $where[] = ['ghost', '=', $filters['ghost']];
        }
        if (isset($filters['ip'])) {
            $where[] = ['ip', '=', $filters['ip']];
        }
        if (isset($filters['username'])) {
            $where[] = ['username', '=', $filters['username']];
        }
        if (isset($filters['realName'])) {
            $where[] = ['real_name', '=', $filters['realName']];
        }
        if (isset($filters['status'])) {
            $where[] = ['status', '=', $filters['status']];
        }
        if (!empty($filters['timeCreatedStart'])) {
            $where[] = ['time_created', '>=', $filters['timeCreatedStart']];
        }
        if (!empty($filters['online'])) {
            $where[] = ['token', '<>', ''];
        }
        if (!empty($filters['timeCreatedEnd'])) {
            $where[] = ['time_created', '<=', $filters['timeCreatedEnd']];
        }
        if (!empty($filters['timeHeartStart'])) {
            $where[] = ['time_heart', '>=', $filters['timeHeartStart']];
        }
        if (isset($filters['staffId'])) {
            $where[] = ['staff_id', '=', $filters['staffId']];
        }
        if (isset($filters['teamId'])) {
            $where[] = ['team_id', '=', $filters['teamId']];
        }
        if (isset($filters['level'])) {
            $where[] = ['level', '=', $filters['level']];
        }
        if (isset($filters['ids'])) {
            $where[] = ['id', 'in', $filters['ids']];
        }
        if (isset($filters['parentId'])) {
            $where[] = ['parent_id', '=', $filters['parentId']];
        }
        if (isset($filters['parentIds'])) {
            $where[] = ['parent_id', 'in', $filters['parentIds']];
        }
        return $where;
    }

    public static function getInvite($ids,$username,$type = 1): array
    {
        $dataSet = [];
        $step = 1;
        while (true) {
            $where = [];
            $where[] = ['parent_id','in',$ids];
            if (!empty($username) && $step == $type) {
                $where[] = ['username','=',$username];
            }
            $dataSet[$step] = Db::table(self::$table)->where($where)->select()->toArray();
            $ids = array_column($dataSet[$step],'id');
            if ($step >= $type) {
                break;
            }
            $step++;
        }
        return $dataSet;
    }

    /**
     * 获取ids
     * @param $ids
     * @param $username
     * @param int $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getInvites($ids,$username,$type = 1,$flag = true): array
    {
        $dataSet = [];
        $returnSet = [];
        $step = 1;
        while (true) {
            $where = [];
            $where[] = ['parent_id','in',$ids];
            if (!empty($username) && $step == $type) {
                $where[] = ['username','=',$username];
            }
            $dataSet[$step] = Db::table(self::$table)->where($where)->select()->toArray();
            $ids = array_column($dataSet[$step],'id');
            foreach ($ids as $id) {
                $returnSet[] = $id;
            }
            if ($step >= $type) {
                break;
            }
            $step++;
        }
        if ($flag) {
            return $returnSet;
        }
        return $dataSet;
    }

    public static function handleMoney($userId,$money,$connect = null,$water = false) {
        $user = self::fetch(intval($userId));
        if (empty($connect)) {
            $connect = Db::connect();
        }
        if ($money >= 0) {
            $newState = [
                'money' => $user['money'] + $money,
            ];
//            $result = $connect->table(self::$table)->where(['id' => $user['id']]);
//                $result->inc('money',$money);
//                dump($result->buildSql());
//                ->save();
            if ($water  == 'caijin') {
                if ($user['water'] >= 0) {
                    $newState['water'] = $money * -1;
                }else{
                    $newState['water'] = $user['water'] + ($money * -1);
                }

//                $result = $result->inc('water_caijin',$money);
            }elseif($water == 'money') {
                if ($user['water'] >= 0) {
                    $newState['water'] = $money * -1;
                }else{
                    $newState['water'] = $user['water'] + ($money * -1);
                }
            }
            $result = self::update(intval($user['id']),$newState);
        }else {
            if (abs($money) > $user['money']) {
                return error(-21,'金额不足扣除');
            }
                  $result = $connect->table(self::$table)->
            where(['id' => $user['id']])->update(['money' => $user['money'] + $money]);
        }
        if (!$result || is_error($result)) {
            return error(-22,'更新金额失败');
        }
        return true;
    }

    public static function clear($userId)
    {
        //orders withdrawals recharges money_logs messages
        self::update(intval($userId),['clear_money' => 1]);
        Order::update(['memberId' => $userId],['existence' => 0]);
        Withdrawal::update(['memberId' => $userId],['existence' => 0]);
        Recharge::update(['memberId' => $userId],['existence' => 0]);
        Log::update(['memberId' => $userId],['existence' => 0]);
        Message::update(['memberId' => $userId],['existence' => 0]);
        return true;
    }

    public static function handlerWater($memberId,$water)
    {
       $where = [];
       $where[] = ['id','=',$memberId];
        try {
            $offect = Db::table(self::$table)
                ->where($where);
            if ($water >= 0) {
                $offect = $offect->inc('water',$water);
            }else{
                $offect = $offect->dec('water',$water);
            }
            $offect = $offect->save();
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return $offect;
    }

    public static function parentIds($id,$step)
    {
        $member = self::fetch(intval($id));

        if (empty($member) || empty($member['parentId'])) {
            return [];
        }
        $returnSet = [];
        $i = 1;

        while (true) {
            $member = self::fetch(intval($member['parentId']));
            if (empty($member)) {
                break;
            }
            $level = Level::fetch(intval($member['level']));
            $rechargeRate = empty($member['v'.$i])?$level['rechargeV'.$i]:$member['v'.$i];
            $waterRate = empty($level['waterV'.$i])?0:$level['waterV'.$i];
            $returnSet[] = ['id' => $member['id'],'rechargeRate' => $rechargeRate,'waterRate' => $waterRate];
            $i++;
            if ($step < $i) {
                break;
            }
        }
        return $returnSet;
    }

    public static function commission($memberId,$money)
    {
        $auto = false;
       $parents = self::parentIds($memberId,3);
        if (!empty($parents)) {
            foreach ($parents as $k=>$parent) {
                $commissionMoney = $money * ($parent['rechargeRate'] / 100);
                $memberInfo = self::fetch(intval($parent['id']));
                $newState = [
                    'commission' => $memberInfo['commission'] + $commissionMoney
                ];
                //两种方案  手动返佣 自动返佣
                if ($auto) {
                    self::handleMoney($parent['id'],$commissionMoney);
                }else{
                    $newState = [
                        'water_padding_money' => $memberInfo['waterPaddingMoney'] + $commissionMoney
                    ];
                }
                self::update(intval($parent['id']),$newState);

                $moneyLogRow = [
                    'memberId' => $memberInfo['id'],
                    'memberMoney' =>$memberInfo['money'],
                    'memberGhost' => $memberInfo['ghost'],
                    'targetId' => $memberId,
                    'type' => 'commission'.($k+1),
                    'money' => $commissionMoney,
                    // 'msg' => "用户id:{$memberId} 充值产生，".($k+1) ."级收益,金额为：{$commissionMoney}",
                    'msg' => "ID người dùng:{$memberId}  được tạo ra.".($k+1) ."Thu nhập cấp, số tiền：{$commissionMoney}",
                    'adminId' => '',
                ];
                Base::addMoneyLog($moneyLogRow); // 更新金额
            }
        }
    }

    public static function water($memberId,$money,$orderNo)
    {
        $parents = self::parentIds($memberId,3);
        if (!empty($parents)) {
            foreach ($parents as $k=>$parent) {
                $commissionMoney = $money * ($parent['waterRate'] / 100);
//                self::handleMoney($parent['id'],$commissionMoney);
                $memberInfo = self::fetch(intval($parent['id']));
                self::update(intval($parent['id']),['water_padding_money' => $memberInfo['waterPaddingMoney'] + $commissionMoney]);
                $moneyLogRow = [
                    'memberId' => $memberInfo['id'],
                    'memberMoney' =>$memberInfo['money'],
                    'memberGhost' => $memberInfo['ghost'],
                    'targetId' => $orderNo,
                    'type' => 'water'.($k+1),
                    'money' => $commissionMoney,
                    // 'msg' => "订单号：{$orderNo} 下单产生，".($k+1) ."级收益,金额为：{$commissionMoney},未发放收益",
                    'msg' => "Số đơn đặt hàng：{$orderNo} được tạo ra，".($k+1) ."Thu nhập cấp, số tiền：{$commissionMoney}, thu nhập không được phát hành",
                    'adminId' => '',
                ];
                Base::addMoneyLog($moneyLogRow); // 更新日志
            }
        }
    }
}
